//
//  AccountInformationViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/6.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "AccountInformationViewController.h"
#import "AccountInformationTableViewCell.h"
#import "WeChatTieTableViewCell.h"
#import "SettingIconViewController.h"
@interface AccountInformationViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UIView * footerView;
@property (nonatomic, strong)NSMutableArray * cellArr;
@property (nonatomic, strong)NSMutableDictionary * contentDic;
@property (nonatomic, strong)UIButton * iconBtn;//头像按钮
@end

@implementation AccountInformationViewController(networking)
//我的信息
- (void)accountInformationData{
    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"phone":[UserModel sharedInstanced].mobile,
                           @"token":[UserModel sharedInstanced].token,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"phone":[UserModel sharedInstanced].mobile,
                               @"token":[UserModel sharedInstanced].token,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userInfo/index?api=api1002"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    if ([compareMD5Str isEqualToString:signResult]) {
                        NSLog(@"成功");
                        self.contentDic = jsonData[@"body"][0];
                        [self.iconBtn sd_setImageWithURL:[NSURL URLWithString:self.contentDic[@"custImg"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"fulezhufang"]];
                        [self.tableView reloadData];
                    }else{
                        NSLog(@"失败");
                        ShowMessage(jsonData[@"msg"]);
                    }
                }else{
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}

@end
@implementation AccountInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"账户信息";
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, 24/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
    
    [self accountInformationData];//网络接口
}

#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT) style:UITableViewStylePlain];
        _tableView.backgroundColor = getColor(grayBGColor);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = self.headerView;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[AccountInformationTableViewCell class] forCellReuseIdentifier:NSStringFromClass([AccountInformationTableViewCell class])];
        [_tableView registerClass:[WeChatTieTableViewCell class] forCellReuseIdentifier:NSStringFromClass([WeChatTieTableViewCell class])];
        _tableView.tableFooterView = self.footerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 56/WIDTH_6_SCALE)];
        _headerView.backgroundColor = [UIColor whiteColor];
        //标题
        UILabel * iconTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 0, 60/WIDTH_6_SCALE, _headerView.height - 1/WIDTH_6_SCALE)];
        [self label:iconTitleLab withFont:DEF_FontSize_12 withText:@"头像" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:_headerView];
        //箭头
        int arrowBtnW = 6/WIDTH_6_SCALE;
        int arrowBtnH = 12/WIDTH_6_SCALE;
        int borderW = 18/WIDTH_6_SCALE;
        UIButton * arrowBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - arrowBtnW - borderW, 0, arrowBtnW, arrowBtnH)];
        [self button:arrowBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:YES withViwe:_headerView];
        arrowBtn.centerY = iconTitleLab.centerY;
        [arrowBtn setImage:[UIImage imageNamed:@"in"] forState:UIControlStateNormal];
        //头像
        int iconBtnW = 32/WIDTH_6_SCALE;
        UIButton * iconBtn = [[UIButton alloc] initWithFrame:CGRectMake(arrowBtn.left - iconBtnW - 5/WIDTH_6_SCALE, 0, iconBtnW, iconBtnW)];
        iconBtn.centerY = iconTitleLab.centerY;
        [self button:iconBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:iconBtnW/2 withMasksToBounds:YES withViwe:_headerView];
        [iconBtn addTarget:self action:@selector(iconBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.iconBtn = iconBtn;
        //分割线
        UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(borderW, _headerView.bottom - 1/WIDTH_6_SCALE, SCREEN_WIDTH - borderW*2, 1/WIDTH_6_SCALE)];
        lineView.backgroundColor = getColor(grayColor);
        [_headerView addSubview:lineView];
    }return _headerView;
}
- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        _footerView.backgroundColor = getColor(grayColor);
    }return _footerView;
}
- (NSMutableArray *)cellArr{
    if (!_cellArr) {
        _cellArr = @[@{@"title":@"用户名"},
                     @{@"title":@"邀请码"},
                     @{@"title":@"手机号"}].mutableCopy;
    }return _cellArr;
}
- (NSMutableDictionary *)contentDic{
    if (!_contentDic) {
        _contentDic = @{}.mutableCopy;
    }return _contentDic;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56/WIDTH_6_SCALE;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if (indexPath.section == 0) {
        AccountInformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AccountInformationTableViewCell class])];
        if (indexPath.row == 1) {
            cell.lineView.hidden = YES;
            cell.titleModel = self.cellArr[1];
            cell.contentLab.text = self.contentDic[@"recomdId"];
        }else{
            cell.titleModel = self.cellArr[0];
            cell.contentLab.text = self.contentDic[@"custName"];
        }
        return cell;
    }else{
        if (indexPath.row == 0) {
            AccountInformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AccountInformationTableViewCell class])];
            cell.titleModel = self.cellArr[2];
            cell.contentLab.text = self.contentDic[@"phone"];
            return cell;
        }else{
            WeChatTieTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WeChatTieTableViewCell class])];
            cell.lineView.hidden = YES;
            if (!self.contentDic[@"openid"] || [self.contentDic[@"openid"] isEqualToString:@""]) {
                [cell.weChatBtn setTitle:@"立即关联" forState:UIControlStateNormal];
            }else{
                [cell.weChatBtn setTitle:self.contentDic[@"openid"] forState:UIControlStateNormal];
            }
            return cell;
        }
    }
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        return 15/WIDTH_6_SCALE;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 15/WIDTH_6_SCALE)];
    sectionView.backgroundColor = getColor(grayBGColor);
    UIView * topBorderLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
    topBorderLineView.backgroundColor = getColor(grayColor);
    [sectionView addSubview:topBorderLineView];
    UIView * bottomBorderLineView = [[UIView alloc] initWithFrame:CGRectMake(0, sectionView.bottom - 1/WIDTH_6_SCALE, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
    bottomBorderLineView.backgroundColor = getColor(grayColor);
    [sectionView addSubview:bottomBorderLineView];
    return sectionView;
}

#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)iconBtnClick:(UIButton *)sender{
    SettingIconViewController * vc = [[SettingIconViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
@end
